const app = getApp()

Component({
  properties: {
    show: { type: Boolean, value: true },
    title: { type: String, value: '' },
    bg: { type: String, value: app.globalData.theme },
    chooseBtn: { type: Boolean, value: app.globalData.chooseBtn },
    homeBtn: { type: Boolean, value: true },
    // true使用相应页面自定义事件，false使用默认事件
    default: { type: Boolean, value: false },
    loading: { type: Boolean, value: false }
  },
  data: {
    statusBarHeight: wx.getStorageSync('statusBarHeight') + 'px',
    menuButtonHeight: wx.getStorageSync('menuButtonHeight') + 'px',
    menuButtonTop: wx.getStorageSync('menuButtonTop') + 2 + 'px',
    navigationBarHeight: wx.getStorageSync('navigationBarHeight') + 'px',
    homeBtnShow: false,
    backBtnShow: false,
    recordShow: false
  },
  ready () {
    this.checkCurrentPage()
  },
  methods: {
    // 验证当前页,设置btnSHow
    checkCurrentPage () {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length-1]
      this.setData({ homeBtnShow: getApp().globalData.index === currentPage.route ? false : true })
      this.setData({ backBtnShow: (pages.length > 1 && !this.properties.homeBtn) ? true : false })
      this.setData({ recordShow: currentPage.route === 'pages/clock/index' ? true : false })
    },
    // 跳转首页
    goHome () {
      // wx.switchTab({ url: '/' + getApp().globalData.index })
      wx.reLaunch({ url: '/' + getApp().globalData.index })
    },
    // 返回上一页
    goBack () {
      wx.navigateBack()
    },
    // 快捷跳转页
    choosePage () {
      if (this.data.default) {
        this.triggerEvent('Default')
      } else {
        const menu = ['个人中心', '捐赠']
        wx.showActionSheet({
          itemList: menu,
          success: (res) => {
            if (menu[res.tapIndex] === '个人中心') {
              if (!this.checkIsCurrent('pages/self/index')) wx.navigateTo({ url: '/pages/self/index' })
            } else if (menu[res.tapIndex] === '捐赠') {
              this.donate()
            }
          }
        })
      }
    },
    addRecord () {
      this.triggerEvent('addRecord')
    },
    // 捐赠
    donate () {
      this.setData({ loading: true })
      app.helper.pay({
        openId: app.globalData.userInfo.openId,
        title: '捐赠',
        fee: 0.01,
        for: 1001
      }).then((res) => {
        if (res.errMsg === 'requestPayment:ok') {
          this.setData({ loading: false })
        }
      }).catch(() => {
        this.setData({ loading: false })
      })
    },
    // 检验目标页是否是当前页
    checkIsCurrent (target = '') {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length-1].route
      return currentPage === target
    }
  }
})
